package com.xm.dao.background;

import com.xm.entity.Matters;
import com.xm.exception.SqlErrorException;
import com.xm.util.BaseUtil;
import org.intellij.lang.annotations.Language;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 事项表Dao
 * @author 康文程
 * @date 2024-1-22 下午 01:45
 */
public class MattersDao extends BaseUtil {
    /**
     * 查询全部事项表
     * @return List<Matters> List对象
     * @throws SqlErrorException 抛出错误
     */
    public List<Matters> getAllMatters() throws SqlErrorException {
        List<Matters> matters = new ArrayList<>();

        @Language("SQL")
        String selectSql = "SELECT * FROM matters where matters_status = 0 order by matters_status = 0 asc ";

        ResultSet resultSet = null;

        try {
            resultSet = executeQuery(selectSql);

            while (resultSet.next()) {
                Integer matterId = resultSet.getInt("matters_id");
                String matterTitle = resultSet.getString("matters_title");
                Integer matterType = resultSet.getInt("matters_type");
                Integer matterStatus = resultSet.getInt("matters_status");
                Date matterDate = resultSet.getDate("matters_date");
                Integer commodityId = resultSet.getInt("commodity_id");

                Matters matter = new Matters(matterId, matterTitle, matterType, matterStatus, matterDate, commodityId);
                matters.add(matter);
            }
        } catch (Exception e) {
            throw new SqlErrorException("查询失败", e);
        } finally {
            close(resultSet);
        }

        return matters;
    }
    /**
     * 根据事项ID删除对应的事项记录
     *
     * @param mattersId 事项ID
     * @return 是否删除成功
     * @throws SqlErrorException SQL执行异常
     */
    public boolean deleteMatterById(Integer mattersId) throws SqlErrorException {
        @Language("SQL")
        String deleteSql = "DELETE FROM matters WHERE matters_id = ?";
        Object[] params = { mattersId };
        int rowsAffected = executeUpdate(deleteSql, params);

        return rowsAffected > 0;
    }
}
